package org.zoomdev.zoom.web.html;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

public final class HtmlBuilder {

    private final List<Element> elements = new ArrayList<>();
    int status = 200;
    private String title;
    private String body;

    public HtmlBuilder title(String title) {
        this.title = title;
        return this;
    }

    public HtmlBuilder status(int status) {
        this.status = status;
        return this;
    }

    public HtmlBuilder body(String body) {
        this.body = body;
        return this;
    }

    public void tag(String tag, String content) {
        this.elements.add(new Element(tag, content));
    }

    public HtmlBuilder pre(String content) {
        tag("pre", content);
        return this;
    }

    public void writeTo(HttpServletResponse response) throws IOException {
        response.setStatus(status);
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.write("<html>");
        writer.write("<head><title>");
        if (title != null) {
            writer.write(title);
        }
        writer.write("</title></head>");
        writer.write("<body>");
        if (body != null) {
            writer.write(body);
        } else {
            for (Element element : elements) {
                element.write(writer);
            }
        }

        writer.write("</body>");
        writer.write("</html>");
    }

    public HtmlBuilder h(String str, int i) {
        tag("h" + i, str);
        return this;
    }

    class Element {

        public String tag;
        public String content;
        public Element sub;

        public Element(String tag, String content) {
            this.tag = tag;
            this.content = content;
        }

        public void write(PrintWriter writer) {
            writer.write("<");
            writer.write(tag);
            writer.write(">");
            if (content != null) {
                writer.write(content);
            } else if (sub != null) {
                sub.write(writer);
            }
            writer.write("</");
            writer.write(tag);
            writer.write(">");
        }
    }
}
